package com.greateffect.littlebud.lib.adapter;

import android.content.Context;
import android.os.Parcelable;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.greateffect.littlebud.lib.utils.JListKit;

import java.util.List;

/**
 * Created by ZengCS on 2019/4/29.
 * function：
 */
public abstract class CommonPagerAdapter<T> extends PagerAdapter {
    private List<T> mItems;
    private List<View> mViewList = JListKit.newArrayList();
    private boolean infiniteCycle;// 无限循环

    public void setInfiniteCycle(boolean infiniteCycle) {
        this.infiniteCycle = infiniteCycle;
    }

    public CommonPagerAdapter(@NonNull Context context, @IdRes int layoutId, List<T> mItems, boolean infiniteCycle) {
        this.infiniteCycle = infiniteCycle;
        this.mItems = mItems;
        initViews(context, layoutId);
    }

    private void initViews(Context context, int layoutId) {
        for (int i = 0; i < mItems.size(); i++) {
            View view = LayoutInflater.from(context).inflate(layoutId, null, false);
            mViewList.add(view);
        }
        // Views集合中的View个数在[2,3]时会存在问题，递归再次填充一遍
        if (infiniteCycle && mViewList.size() > 1 && mViewList.size() < 4) {
            initViews(context, layoutId);
        }
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        if (null == mItems) {
            return 0;
        } else if (mItems.size() == 1) {
            return 1;
        }
        return infiniteCycle ? Short.MAX_VALUE : mItems.size();
    }

    private int getRealPosition(int position) {
        if (infiniteCycle)
            return position % mItems.size();
        return position;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        View rootView = mViewList.get(position % mViewList.size());

        int realPosition = getRealPosition(position);
        convert(rootView, mItems.get(realPosition), realPosition);
        container.addView(rootView);
        return rootView;
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    public abstract void convert(View view, T item, int position);
}
